const jsonwebtoken = require('jsonwebtoken');
const config = require('../../config/config.jwt');

module.exports = () => {
  return async function jwt(ctx, next) {
    if (!config.enable){
      ctx.user = await ctx.app.mysql.get('user', {username:'admin'});
      return await next();
    }
    if (!config.whiteList.includes(ctx.path)) {
      try {
        ctx.user = await jsonwebtoken.verify(ctx.headers.authorization, config.secret);
      } catch (error) {
        if (error.name === 'TokenExpiredError') {
          return ctx.fail('令牌超时', 1001);
        }
        if (error.name === 'JsonWebTokenError') {
          return ctx.fail('令牌校验失败', 1001);
        }
        return ctx.fail();
      }
    }

    return await next();
  }
}